package com.qtenv.datasync.api.shanke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.HashMap;
import java.util.Map;

public class ShanKeApi {
    private final static String host = "http://218.75.104.131:85/SeckV3CommService/api";
    private final static String appId = "seck00001";
    private final static String loginName = "gzzc";
    private final static String password = "4514571963EB0D418C5307773C3CC4F5";

    private static JSONObject post(String url, Map<String, Object> paramMap, boolean header) {
        HttpRequest post = HttpUtil.createPost(host + url);

        if (header) {
            post.header("token", getToken());
        }

        String result = post.contentType("application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
        return JSONUtil.parseObj(result);
    }

    private static JSONObject post(String url, Map<String, Object> paramMap) {
        return post(url, paramMap, true);
    }

    private static JSONObject postNoHeader(String url, Map<String, Object> paramMap) {
        return post(url, paramMap, false);
    }

    private static JSONObject login() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("AppId", appId);
        paramMap.put("LoginName", loginName);
        paramMap.put("Password", password);

        return postNoHeader("/Auth/Login", paramMap);
    }

    private static String getToken() {
        return login().getJSONObject("Data").getStr("token");
    }

    /**
     * 获取水表时间段内所有数据
     *
     * @param commAddr
     * @param startTime
     * @param endTime
     * @return
     */
    public static JSONObject getMeterHisData(String commAddr, String startTime, String endTime) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("CommAddr", commAddr);
        paramMap.put("StartDate", startTime);
        paramMap.put("EndDate", endTime);
        return post("/MeterData/GetMeterHisData", paramMap);
    }

    public static void main(String[] args) {
//        System.out.println(getToken());
        JSONArray jsonArray = getMeterHisData("0000392203048112", "2022-12-31", "2022-12-31").getJSONArray("Data");
        System.out.println(jsonArray);
    }
}
